package com.example.everying.framework.ai.doubao;

import com.example.everying.framework.ai.deepseek.domain.DeepSeekRequestDto;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;

@Component
public class AiDouBaoUtils {

    private final String apiKey;  // 改为存储配置，而非连接实例
    private final String endpointId;

    public AiDouBaoUtils(
            @Value("${ai.douBao.apiKey}")  String apiKey,
            @Value("${ai.douBao.endpointId}")  String endpointId) {
        this.apiKey  = apiKey;
        this.endpointId  = endpointId;
    }
    /**
     * 单轮对话（自动创建连接）
     */
    public String douBaoSingleChat(DeepSeekRequestDto dto) {
        ArkService service = null;  // 每次请求新建连接
        try {
            service = createNewConnection();  // 创建新连接
            ChatCompletionRequest request = buildSingleRequest(dto.getContent());
            System.out.println("AI 请求内容: " + request);  // 打印请求内容
            String response = executeRequest(service, request);
            System.out.println("AI 响应内容: " + response);  // 打印响应内容
            return response;
        } finally {
            if (service != null) service.shutdownExecutor();   // 确保关闭连接
        }
    }

    /**
     * 多轮对话（自动创建连接）
     */
    public String douBaoMultiTurnChat(List<ChatMessage> history) {
        ArkService service = null;
        try {
            service = createNewConnection();  // 创建新连接
            ChatCompletionRequest request = buildMultiTurnRequest(history);
            return executeRequest(service, request);
        } finally {
            if (service != null) service.shutdownExecutor();   // 确保关闭连接
        }
    }

    //--- 私有方法 ---//
    private ArkService createNewConnection() {
        return ArkService.builder()
                .apiKey(apiKey)
                .connectTimeout(Duration.ofSeconds(2))
                .build();
    }

    private ChatCompletionRequest buildSingleRequest(String content) {
        return ChatCompletionRequest.builder()
                .model(endpointId)
                .messages(List.of(
                        ChatMessage.builder()
                                .role(ChatMessageRole.USER)
                                .content(buildPrompt(content))
                                .build()))
                .build();
    }

    private ChatCompletionRequest buildMultiTurnRequest(List<ChatMessage> history) {
        return ChatCompletionRequest.builder()
                .model(endpointId)
                .messages(history)
                .build();
    }

    private String executeRequest(ArkService service, ChatCompletionRequest request) {
        long startTime = System.currentTimeMillis();
        String response = service.createChatCompletion(request)
                .getChoices()
                .get(0)
                .getMessage()
                .getContent()
                .toString();
        System.out.println("AI  响应时间: " + (System.currentTimeMillis()  - startTime) + "ms");
        return response;
    }



//    private final ArkService service;
//    private final String endpointId;
//
//    public AiDouBaoUtils(
//            @Value("${ai.douBao.apiKey}") String apiKey,
//            @Value("${ai.douBao.endpointId}") String endpointId) {
//        this.service = ArkService.builder()
//                .apiKey(apiKey)
//                .connectTimeout(Duration.ofSeconds(2))  //使用Duration设置2秒超时
//                .build();
//        this.endpointId = endpointId;
//    }
//
//    public String douBaoSingleChat(DeepSeekRequestDto dto) {
//        long startTime = System.currentTimeMillis();  // 记录开始时间
//        try {
//            ChatCompletionRequest request = ChatCompletionRequest.builder()
//                    .model(endpointId)
//                    .messages(List.of(
//                            ChatMessage.builder()
//                                    .role(ChatMessageRole.USER)
//                                    .content(buildPrompt(dto.getContent()))
//                                    .build()))
//                    .build();
//
//            String response = service.createChatCompletion(request)
//                    .getChoices()
//                    .get(0)
//                    .getMessage()
//                    .getContent()
//                    .toString();
//
//            // 打印响应时间
//            long elapsedTime = System.currentTimeMillis() - startTime;
//            System.out.println("AI 响应时间: " + elapsedTime + "ms"); // 简单打印
//
//            return response;
//        } catch (Exception e) {
//            throw new RuntimeException("AI调用失败", e);
//        }
//    }
//
//    public String douBaoMultiTurnChat(List<ChatMessage> history) {
//        long startTime = System.currentTimeMillis();
//        try {
//            ChatCompletionRequest request = ChatCompletionRequest.builder()
//                    .model(endpointId)
//                    .messages(history) // 直接使用传入的历史消息
//                    .build();
//
//            String response = service.createChatCompletion(request)
//                    .getChoices()
//                    .get(0)
//                    .getMessage()
//                    .getContent()
//                    .toString();
//
//            long elapsedTime = System.currentTimeMillis() - startTime;
//            System.out.println("AI 响应时间: " + elapsedTime + "ms");
//
//            return response;
//        } catch (Exception e) {
//            throw new RuntimeException("AI调用失败", e);
//        }
//    }
//
//    @PreDestroy
//    public void shutdown() {
//        if (service != null) {
//            service.shutdownExecutor();
//        }
//    }

    /**
     * 构建提示词
     */
    private static String buildPrompt(String content) {
//        return String.format(
//                "为以下文本生成一个15字以内的标题，要求简短有力，必须包含关键信息（如时间、地点、事件等），仅输出标题内容：%s",
//                content
//        );
        return String.format(
                "你现在是一名语言总结大师，请为我以下文本生成一个不多于15字的标题，必须包含关键信息（如时间、地点、事件等），" +
                        "且如果文本本身内容很少，没有表达清楚意思，只需输出和原来文本内容一样的标题即可，要求仅输出标题内容：%s",
                content
        );
    }
}
